package com.china_goldcard.choosedialog;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择对话框
 */
public class ChooseDialog extends DialogFragment {

    private int itemH = 44;

    private int titleH = 44;

    private int btnH = 44;

    private int itemW = 200;

    private String title = "请选择";

    private String btn = "更多";

    private TextView titleTv;

    private TextView btnTv;

    private boolean cancelable = true;

    private ChooseDialogModel data;

    private RecyclerView recyclerView;

    private int maxItemCount = 3;

    private List<ChooseDialogItem> items = new ArrayList<>();

    private ChooseDialogAdapter adapter;

    private boolean setupHeight = false;

    private OnClickListener clickListener;

    private int selectIcon;

    public interface OnClickListener{
        void onItemClick(ChooseDialog dialog,ChooseDialogItem item);
        void onBtnClick(ChooseDialog dialog,ChooseDialogItem item);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE,R.style.ChooseDialog);
        initData();
        setCancelable(cancelable);
    }

    @Override
    public void onAttach(Activity activity) {
        if (activity instanceof OnClickListener) {
            clickListener = (OnClickListener)activity;
        }
        super.onAttach(activity);
    }

    @Override
    public void onAttach(Context context) {
        if (context instanceof OnClickListener) {
            clickListener = (OnClickListener)context;
        }
        super.onAttach(context);
    }

    /**
     * 初始化数据
     */
    private void initData(){
        Bundle bundle = getArguments();
        if (bundle != null){
            this.data = (ChooseDialogModel)bundle.getSerializable("data");
        }
        if (this.data != null){
            items.clear();
            items.addAll(this.data.getDataList());
            itemH = this.data.getItemH();
            itemW = this.data.getItemW();
            title = trimNull(data.getTitle(),title);
            btn = trimNull(data.getBtn(),btn);
            cancelable = data.isCancelable();
            maxItemCount = data.getMaxItemCount();
            selectIcon = data.getSelectIcon();
        }
    }

    /**
     * 更新UI
     */
    private void updateUI(){
        titleTv.setText(title);
        btnTv.setText(btn);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.choose_dialog_view, container);
        titleTv = (TextView) view.findViewById(R.id.choose_dialog_title_tv);
        btnTv = (TextView) view.findViewById(R.id.choose_dialog_btn_tv);
        recyclerView = (RecyclerView)view.findViewById(R.id.choose_dialog_content);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ChooseDialogAdapter(getContext(),items);
        adapter.setOnClickListener(new ChooseDialogAdapter.OnClickListener() {
            @Override
            public void onItemClick(ChooseDialogItem item) {
                if (clickListener!=null){
                    clickListener.onItemClick(ChooseDialog.this,item);
                }
            }
        });
        recyclerView.setAdapter(adapter);
        adapter.setItemH(dip2px(getContext(),itemH));
        adapter.setSelectIcon(selectIcon);
        btnTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 if (clickListener!=null){
                     ChooseDialogItem cItem = null;
                     for(ChooseDialogItem item:items){
                           if (item.isSelected()){
                               cItem = item;
                               break;
                           }
                     }
                     if (cItem == null && items.size() > 0){
                         cItem = items.get(0);
                     }
                     clickListener.onBtnClick(ChooseDialog.this,cItem);
                 }
            }
        });
        updateUI();
        return view;
    }

    /**
     * trimNull
     * @param str
     * @param defaultStr
     * @return
     */
    private String trimNull(String str,String defaultStr){
        if (str!=null && str.length() > 0){
            return str.trim();
        }else{
            return defaultStr;
        }
    }

    /**
     * 新建
     * @param context
     * @param model
     * @return
     */
    public static ChooseDialog newInstance(Context context,ChooseDialogModel model){
        Bundle args = new Bundle();
        args.putSerializable("data",model);
        ChooseDialog dialog = new ChooseDialog();
        dialog.setArguments(args);
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!setupHeight){
            setupHeight = true;
            btnTv.getLayoutParams().height = dip2px(getContext(),btnH);
            titleTv.getLayoutParams().height = dip2px(getContext(),titleH);
            int contentW = itemW == 0 ? ViewGroup.LayoutParams.MATCH_PARENT : dip2px(getContext(),itemW);
            int contentH = Math.min(items.size(),maxItemCount) * dip2px(getContext(),itemH) + dip2px(getContext(),titleH) + dip2px(getContext(),btnH);
            getDialog().getWindow().setLayout(contentW,contentH);
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     * @param context
     * @param dpValue 要转换的dp值
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * @param context
     * @param pxValue 要转换的px值
     */
    private int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
